<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>日历</title>
    <style>
      body {
        display: flex;
        flex-direction: column;
        min-height: 100vh;
        background-image: url("{{ url_for('static', filename='素材/背景图.png') }}");
        background-size: cover;
        background-position: center;
        color: white;
        font-family: Arial, sans-serif;
        margin: 0;
        padding: 0;
        overflow-x: hidden;
      }

      .header,
      .footer,
      .info-container,
      .calendar-container,
      .data-container {
        max-width: 100%;
        box-sizing: border-box;
      }

      .container {
        max-width: 100%;
        max-height: 100%;
        overflow: auto;
      }

      * {
        box-sizing: border-box;
      }

      .footer {
        display: flex;
        height: 80px;
        background-color: #1c023f;
        justify-content: space-between;
        align-items: center;
        padding: 10px 20px;
        margin-top: auto;
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        width: 100%;
        z-index: 1000;
      }

      .header {
        display: flex;
        height: 90px;
        width: 100%;
        background-color: #1c023f;
        justify-content: space-between;
        align-items: center;
        padding: 0 20px;
      }

      .header h1,
      .header p {
        margin: 0;
      }

      .calendar-info {
        margin: 10px 5px;
        height: auto;
        line-height: 3;
      }

      .info-container {
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        background-color: rgba(129, 133, 173, 0.5);
        padding: 10px;
        border-radius: 8px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        width: 95%;
        text-align: left;
        height: auto;
        margin: 10px;
        margin-left: auto;
        margin-right: auto;
        flex: 4;
      }

      .main-container {
        display: flex;
        align-items: center;
        justify-content: space-between;
        align-items: stretch;
        gap: 10px;
        background-color: rgba(129, 133, 173, 0.5);
        padding: 10px;
        border-radius: 8px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        width: 95%;
        height: auto;
        margin: 10px 10px;
        margin-bottom: 100px;
        overflow-y: auto;
      }

      .data-container {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 10px;
        flex: 4;
        /* 占据剩余空间 */
      }

      .calendar-container {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 20px;
      }

      .button {
        background: rgba(107, 85, 180, 0.7);
        opacity: 0.6;
        border: none;
        border-radius: 10px;
        color: white;
        padding: 12px;
        text-align: center;
        margin: 10px 20px;
        cursor: pointer;
      }

      .button:hover {
        background: #5b4aa3;
      }

      .footer svg {
        color: white;
        font-size: 24px;
      }

      button img {
        display: block;
        max-width: 100%;
        height: auto;
      }

      .back-btn,
      .location-btn,
      .calendar-btn,
      .moon-btn,
      .data-btn,
      .index-btn {
        margin-right: 10px;
        background: none;
        border: none;
        padding: 0;
        cursor: pointer;
      }

      .location-btn {
        margin-left: 10px;
        background: none;
        border: none;
        padding: 0;
        cursor: pointer;
      }

      .location-info {
        flex-grow: 1;
        text-align: right;
        padding: 30px;
      }

      .location-info h1,
      .location-info p {
        margin: 0;
      }

      .content {
        padding: 20px;
        background: #2e1a5a;
        border-radius: 10px;
        margin: 20px;
        color: white;
        max-width: 100%;
        width: 100%;
        box-sizing: border-box;
      }

      .calendar-header {
        display: flex;
        justify-content: space-between;
        width: 100%;
        margin-bottom: 20px;
      }

      .calendar-header button {
        background: none;
        border: none;
        padding: 0;
        margin: 0;
        cursor: pointer;
      }

      .calendar-header button img {
        width: 20px;
        height: 20px;
        display: block;
      }

      .calendar-days {
        display: grid;
        grid-template-columns: repeat(7, minmax(30px, 1fr));
        gap: 5px;
        width: 100%;
        overflow-x: auto;
      }

      .calendar-day {
        background-color: rgba(206, 204, 210, 0.2);
        padding: 10px;
        border-radius: 3px;
        text-align: center;
        cursor: pointer;
        margin: 3px;
        color: white;
      }

      .column {
        flex: 1;
        max-width: 20%;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .calendar-day:hover {
        background-color: #5b4aa3;
      }

      .calendar-day.today {
        background-color: rgba(97, 167, 229, 0.6);
      }

      .calendar-day.selected {
        background-color: #5b4aa3;
        border: 2px solid #fff;
      }

      @media (max-width: 768px) {
        .calendar-day {
          padding: 5px;
          /* 进一步减少 padding */
          font-size: 14px;
          /* 缩小字体 */
        }

        .calendar-days {
          gap: 5px;
          /* 进一步减少间距 */
        }
      }

      .info-item {
        display: flex;
        align-items: center;
        gap: 10px;
      }

      .info-item img {
        width: 50px;
        height: auto;
      }

      .info-item span {
        font-size: 16px;
        color: #fff;
      }

      .city-button {
        width: 50px;
        height: 50px;
        border-radius: 50%;
        background-color: #2593d7;
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 14px;
        text-decoration: none;
        cursor: pointer;
        flex-shrink: 0;
      }

      .city-button:hover {
        background-color: #2e1a5a;
      }

      /* 五要素数据样式 */
      .five-elements-container {
        display: flex;
        flex-direction: column;
        gap: 10px;
        margin-top: 10px;
        padding: 10px;
        background-color: rgba(120, 124, 166, 0);
        border-radius: 8px;
      }

      .five-elements-title {
        font-size: 18px;
        font-weight: bold;
        color: #ffffff;
        margin-bottom: 5px;
      }

      .five-elements-grid {
        display: grid;
        grid-template-columns: repeat(5, 1fr);
        gap: 2px;
      }

      .five-elements-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        text-align: center;
      }

      .five-elements-label {
        font-size: 12px;
        color: #2b2766c7;
        text-align: center;
        font-weight: 600;
      }

      .five-elements-value {
        font-size: 16px;
        color: #fff;
        white-space: pre-line;
        text-align: center;
      }

      .calendar-info-container {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
      }

      .calendar-info-left {
        flex: 1;
        min-width: 300px;
      }

      .calendar-info-right {
        flex: 1;
        min-width: 300px;
      }
    </style>
  </head>

  <body>
    <div class="header">
      <button
        class="back-btn"
        onclick="window.location.href='newcalendar.html'"
      >
        <img
          src="{{ url_for('static', filename='素材/left.png') }}"
          alt="Back"
        />
      </button>
      <div class="location-info">
        <h4 id="location-name">北京</h4>
        <p id="coordinates">116.4074°E 39.9042°N</p>
      </div>

      <button
        class="location-btn"
        onclick="window.location.href='direction.html'"
      >
        <img
          src="{{ url_for('static', filename='素材/箭头.png') }}"
          alt="Location"
        />
      </button>
    </div>

    <div class="calendar-container" id="calendar-container">
      <!-- 日历内容会动态生成 -->
    </div>

    <div id="info-container" class="info-container">
      <div class="calendar-info-container">
        <div class="calendar-info-left">
          <div id="tibetan-calendar">藏历: 请选择日期</div>
          <div id="gregorian-calendar">公历: 请选择日期</div>
          <div id="lunar-calendar">农历: 请选择日期</div>
        </div>
        <div class="calendar-info-right">
          <div id="five-elements-container" class="five-elements-container">
            <div class="five-elements-title">五要素</div>
            <div class="five-elements-grid">
              <div class="five-elements-item">
                <span class="five-elements-label">定曜</span>
                <span class="five-elements-value" id="ding-yao">--</span>
              </div>
              <div class="five-elements-item">
                <span class="five-elements-label">太阳日月宿</span>
                <span class="five-elements-value" id="taiyang-riyuexiu"
                  >--</span
                >
              </div>
              <div class="five-elements-item">
                <span class="five-elements-label">定日</span>
                <span class="five-elements-value" id="ding-ri">--</span>
              </div>
              <div class="five-elements-item">
                <span class="five-elements-label">会合</span>
                <span class="five-elements-value" id="hui-he">--</span>
              </div>
              <div class="five-elements-item">
                <span class="five-elements-label">作用</span>
                <span class="five-elements-value" id="zuo-yong">--</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="main-container">
      <div class="column">
        <a href="direction.html" class="city-button" id="location-name2"
          >北京</a
        >
      </div>
      <div class="data-container">
        <div class="info-item">
          <img
            src="{{ url_for('static', filename='素材/日升.png') }}"
            alt="日升"
          />
          <span id="sunrise-time">日出: --:--</span>
        </div>
        <div class="info-item">
          <img
            src="{{ url_for('static', filename='素材/日落.png') }}"
            alt="日落"
          />
          <span id="sunset-time">日落: --:--</span>
        </div>
        <div class="info-item">
          <img
            src="{{ url_for('static', filename='素材/月升.png') }}"
            alt="月升"
          />
          <span id="moonrise-time">月出: --:--</span>
        </div>
        <div class="info-item">
          <img
            src="{{ url_for('static', filename='素材/月落.png') }}"
            alt="月落"
          />
          <span id="moonset-time">月落: --:--</span>
        </div>
      </div>
    </div>

    <div class="footer">
      <button
        class="calendar-btn"
        onclick="window.location.href='newcalendar.html'"
      >
        <img
          src="{{ url_for('static', filename='素材/日历.png') }}"
          alt="calendar"
        />
      </button>
      <button class="moon-btn" onclick="window.location.href='十二宫图.html'">
        <img
          src="{{ url_for('static', filename='素材/可视化浅色.png') }}"
          alt="moon"
        />
      </button>
      <button class="data-btn" onclick="window.location.href='newdata.html'">
        <img
          src="{{ url_for('static', filename='素材/知识浅色.png') }}"
          alt="data"
        />
      </button>
      <button class="index-btn" onclick="window.location.href='newai.html'">
        <img
          src="{{ url_for('static', filename='素材/大模型.png') }}"
          alt="index"
        />
      </button>
    </div>

    <script>
      let calendarData = [];
      // 添加天文数据缓存对象
      let celestialDataCache = {};
      // 五要素数据缓存
      let fiveElementsCache = {};
      // 当前城市ID
      let currentCityId = 1;
      // 当前城市名称
      let currentCityname = "北京市";

      // 加载 JSON 文件并初始化日历数据
      async function loadCalendarData() {
        try {
          const response = await fetch("tibetan_lunar_calendar_2023_2030.json"); // JSON 文件路径
          if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
          }
          calendarData = await response.json();
          console.log(
            "日历数据加载成功，共加载 " + calendarData.length + " 条记录"
          );
        } catch (error) {
          console.error("加载日历数据失败:", error);
          // 如果加载失败，使用模拟数据
          alert("无法加载日历数据，将使用模拟数据。");
        }
      }

      // 加载五要素数据
      async function loadFiveElementsData() {
        try {
          const currentYear = new Date().getFullYear();
          const response = await fetch(
            `calendar_data/calendar_${currentYear}.json`
          );
          if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
          }
          fiveElementsCache[currentYear] = await response.json();
          console.log(`${currentYear}年五要素数据加载成功`);
        } catch (error) {
          console.error("加载五要素数据失败:", error);
        }
      }

      async function loadCelestialData(city) {
        try {
          // 如果已经缓存了该城市的数据，则直接返回
          if (celestialDataCache[city.id]) {
            console.log(`使用缓存的天文数据: ${city.name}`);
            currentCityId = city.id; // 设置当前城市ID
            return;
          }

          // 正确构建文件路径 - 使用city.dataFile，它已经包含了完整的文件名
          const response = await fetch(`celestial_data/${city.dataFile}`);

          if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
          }

          const data = await response.json();
          celestialDataCache[city.id] = data;
          currentCityId = city.id; // 设置当前城市ID
          console.log(`${city.name}的天文数据加载成功`);
        } catch (error) {
          console.error(`加载${city.name}的天文数据失败:`, error);
        }
      }

      async function loadCityIndex() {
        try {
          const response = await fetch("../celestial_data/city_index.json");
          if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
          }

          // 从localStorage获取城市名称，如果没有则使用默认值
          currentCityname = localStorage.getItem("locationName") || "北京市";
          console.log("当前城市:", currentCityname);

          const cityIndex = await response.json();
          console.log("城市索引加载成功，共 " + cityIndex.length + " 个城市");

          // 加载当前城市的天文数据
          const currentCity = cityIndex.find(
            (city) => city.name === currentCityname
          );
          if (currentCity) {
            await loadCelestialData(currentCity);
          } else {
            console.error(`未找到城市: ${currentCityname}`);
            // 如果找不到指定城市，使用第一个城市
            if (cityIndex.length > 0) {
              await loadCelestialData(cityIndex[0]);
            }
          }
        } catch (error) {
          console.error("加载城市索引失败:", error);
        }
      }

      window.onload = async function () {
        if (
          localStorage.getItem("locationName") &&
          localStorage.getItem("coordinates")
        ) {
          document.getElementById("location-name").innerText =
            localStorage.getItem("locationName");
          document.getElementById("coordinates").innerText =
            localStorage.getItem("coordinates");
          document.getElementById("location-name2").innerText =
            localStorage.getItem("locationName");
        }

        // 加载日历数据
        await loadCalendarData();
        // 加载五要素数据
        await loadFiveElementsData();
        // 初始化日历并显示今天的信息
        await loadCityIndex();

        const today = new Date();
        generateCalendar(today.getMonth(), today.getFullYear());
        updateDateInfo(today.getDate(), today.getMonth(), today.getFullYear());
      };

      const today = new Date();
      let currentMonth = today.getMonth();
      let currentYear = today.getFullYear();
      let selectedDay = today.getDate();

      let selectedMonth = currentMonth;
      let selectedYear = currentYear;

      const months = [
        "1月",
        "2月",
        "3月",
        "4月",
        "5月",
        "6月",
        "7月",
        "8月",
        "9月",
        "10月",
        "11月",
        "12月",
      ];

      // 获取特定日期的日历数据
      function getCalendarData(day, month, year) {
        // 格式化日期为 YYYY-MM-DD
        const dateStr = `${year}-${String(month + 1).padStart(2, "0")}-${String(
          day
        ).padStart(2, "0")}`;
        // 在加载的数据中查找匹配的日期
        const foundData = calendarData.find((item) => item.date === dateStr);
        return {
          tibetanCalendar: `藏历 ${foundData.tibetan_year}年 ${foundData.tibetan_month}月 ${foundData.tibetan_day}`,
          gregorianCalendar: `公历 ${year}年${month + 1}月${day}日 ${
            foundData.weekday
          }`,
          lunarCalendar: `农历 ${foundData.lunar_date}`,
          //eventInfo: getEventInfo(day, month, year), // 获取事件信息
          dayLeap: foundData.day_leap,
          monthLeap: foundData.month_leap,
          dayMiss: foundData.day_miss,
          // 计算日出日落时间
        };
      }

      // 获取五要素数据
      function getFiveElementsData(day, month, year) {
        // 检查是否有该年份的数据缓存
        if (!fiveElementsCache[year]) {
          console.error(`没有${year}年的五要素数据缓存`);
          return null;
        }

        // 获取该月的数据
        const monthData = fiveElementsCache[year][month + 1];
        if (!monthData) {
          console.error(`没有${year}年${month + 1}月的五要素数据`);
          return null;
        }

        // 获取该日的数据
        const dayData = monthData[day];
        if (!dayData || dayData.error) {
          console.error(
            `没有${year}年${month + 1}月${day}日的五要素数据或数据有错误`
          );
          return null;
        }

        return dayData;
      }

      // 格式化五要素数据显示
      function formatFiveElementsValue(values) {
        if (!values || !Array.isArray(values)) return "--";
        return values.join("\n");
      }

      // 获取指定日期的天文数据
      function getCelestialDataForDate(day, month, year) {
        // 如果没有缓存数据，返回默认值
        if (!celestialDataCache[currentCityId]) {
          console.error("没有天文数据缓存");
          return {
            sunriseTime: "--:--",
            sunsetTime: "--:--",
            moonriseTime: "--:--",
            moonsetTime: "--:--",
          };
        }

        // 格式化日期为 YYYY-MM-DD
        const dateStr = `${year}-${String(month + 1).padStart(2, "0")}-${String(
          day
        ).padStart(2, "0")}`;

        // 在缓存数据中查找匹配的日期
        const foundData = celestialDataCache[currentCityId].data.find(
          (item) => item.date === dateStr
        );

        if (foundData) {
          return foundData;
        } else {
          console.error(`未找到日期 ${dateStr} 的天文数据`);
          return {
            sunriseTime: "--:--",
            sunsetTime: "--:--",
            moonriseTime: "--:--",
            moonsetTime: "--:--",
          };
        }
      }

      // 备用数据函数
      function getFallbackCalendarData(day, month, year) {
        const date = new Date(year, month, day);
        const formattedDate = `${year}年${month + 1}月${day}日`;

        // 模拟藏历数据
        const tibetanYear = year - 127; // 简单模拟
        const tibetanMonth = ((month + 2) % 12) + 1;
        const tibetanDay = ((day + 15) % 30) + 1;
        const tibetanCalendar = `藏历 ${tibetanYear}年 ${tibetanMonth}月 ${tibetanDay}日`;

        // 公历数据
        const weekDays = [
          "星期日",
          "星期一",
          "星期二",
          "星期三",
          "星期四",
          "星期五",
          "星期六",
        ];
        const gregorianCalendar = `公历 ${formattedDate} ${
          weekDays[date.getDay()]
        }`;

        // 模拟农历数据
        const lunarMonths = [
          "正",
          "二",
          "三",
          "四",
          "五",
          "六",
          "七",
          "八",
          "九",
          "十",
          "冬",
          "腊",
        ];
        const lunarDays = [
          "初一",
          "初二",
          "初三",
          "初四",
          "初五",
          "初六",
          "初七",
          "初八",
          "初九",
          "初十",
          "十一",
          "十二",
          "十三",
          "十四",
          "十五",
          "十六",
          "十七",
          "十八",
          "十九",
          "二十",
          "廿一",
          "廿二",
          "廿三",
          "廿四",
          "廿五",
          "廿六",
          "廿七",
          "廿八",
          "廿九",
          "三十",
        ];
        const lunarMonth = lunarMonths[(month + 3) % 12];
        const lunarDay = lunarDays[(day - 1) % 30];
        const lunarCalendar = `农历 ${lunarMonth}月${lunarDay}`;

        // 模拟事件信息
        const eventInfo = getEventInfo(day, month, year);

        return {
          tibetanCalendar,
          gregorianCalendar,
          lunarCalendar,
          eventInfo,
          dayLeap: false,
          monthLeap: false,
          dayMiss: false,
        };
      }

      // 获取事件信息
      function getEventInfo(day, month, year) {
        let eventInfo = "无特殊事件";

        // 固定日期的节日（公历）
        if (month === 0 && day === 1) eventInfo = "元旦";
        else if (month === 1 && day === 14) eventInfo = "情人节";
        else if (month === 2 && day === 8) eventInfo = "国际妇女节";
        else if (month === 2 && day === 12) eventInfo = "植树节";
        else if (month === 3 && day === 1) eventInfo = "愚人节";
        else if (month === 4 && day === 1) eventInfo = "劳动节";
        else if (month === 4 && day === 4) eventInfo = "青年节";
        else if (month === 4 && day === 12) eventInfo = "护士节";
        else if (month === 5 && day === 1) eventInfo = "儿童节";
        else if (month === 7 && day === 1) eventInfo = "建军节";
        else if (month === 7 && day === 7) eventInfo = "七夕节";
        else if (month === 8 && day === 10) eventInfo = "教师节";
        else if (month === 9 && day === 1) eventInfo = "国庆节";
        else if (month === 11 && day === 25) eventInfo = "圣诞节";

        // 特殊计算的节日（如母亲节、父亲节等）
        const specialFestival = calculateSpecialFestivals(day, month, year);
        if (specialFestival) {
          eventInfo = specialFestival;
        }

        return eventInfo;
      }

      function updateDateInfo(day, month, year) {
        // 更新选中状态
        selectedDay = day;
        selectedMonth = month;
        selectedYear = year;
        // 获取日期相关数据
        const data = getCalendarData(day, month, year);

        // 更新显示
        document.getElementById("tibetan-calendar").textContent =
          data.tibetanCalendar;
        document.getElementById("gregorian-calendar").textContent =
          data.gregorianCalendar;
        document.getElementById("lunar-calendar").textContent =
          data.lunarCalendar;

        // 获取并更新天文数据
        const celestialData = getCelestialDataForDate(day, month, year);
        document.getElementById(
          "sunrise-time"
        ).textContent = `日出: ${celestialData.sunriseTime}`;
        document.getElementById(
          "sunset-time"
        ).textContent = `日落: ${celestialData.sunsetTime}`;
        document.getElementById(
          "moonrise-time"
        ).textContent = `月出: ${celestialData.moonriseTime}`;
        document.getElementById(
          "moonset-time"
        ).textContent = `月落: ${celestialData.moonsetTime}`;

        // 获取并更新五要素数据
        const fiveElementsData = getFiveElementsData(day, month, year);
        if (fiveElementsData) {
          document.getElementById("ding-yao").textContent =
            formatFiveElementsValue(fiveElementsData["定曜"]);
          document.getElementById("taiyang-riyuexiu").textContent =
            formatFiveElementsValue(fiveElementsData["太阳日月宿"]);
          document.getElementById("ding-ri").textContent =
            formatFiveElementsValue(fiveElementsData["定日"]);
          document.getElementById("hui-he").textContent =
            formatFiveElementsValue(fiveElementsData["会合"]);
          document.getElementById("zuo-yong").textContent =
            fiveElementsData["作用"].join("\n") || "--";
        } else {
          // 如果没有五要素数据，显示默认值
          document.getElementById("ding-yao").textContent = "--";
          document.getElementById("taiyang-riyuexiu").textContent = "--";
          document.getElementById("ding-ri").textContent = "--";
          document.getElementById("hui-he").textContent = "--";
          document.getElementById("zuo-yong").textContent = "--";
        }

        // 更新日历中选中的日期样式
        updateCalendarSelection();
      }

      function updateCalendarSelection() {
        // 移除所有选中样式
        const allDays = document.querySelectorAll(".calendar-day");
        allDays.forEach((day) => {
          if (day.classList.contains("selected")) {
            day.classList.remove("selected");
          }
        });

        // 如果当前显示的月份和年份与选中的相同，则添加选中样式
        if (currentMonth === selectedMonth && currentYear === selectedYear) {
          const dayElements = document.querySelectorAll(
            ".calendar-day:not(.disabled)"
          );
          for (let i = 0; i < dayElements.length; i++) {
            if (parseInt(dayElements[i].textContent) === selectedDay) {
              dayElements[i].classList.add("selected");
              break;
            }
          }
        }
      }

      function generateCalendar(month, year) {
        const firstDay = new Date(year, month).getDay();
        const daysInMonth = new Date(year, month + 1, 0).getDate();
        const calendarContainer = document.getElementById("calendar-container");
        calendarContainer.innerHTML = "";

        const calendarHeader = document.createElement("div");
        calendarHeader.classList.add("calendar-header");

        const prevYearBtn = document.createElement("button");
        const prevYearImg = document.createElement("img");
        prevYearImg.src =
          "{{ url_for('static', filename='素材/doubleleft.png') }}";
        prevYearImg.alt = "Previous Year";
        prevYearBtn.appendChild(prevYearImg);
        prevYearBtn.onclick = () => changeYear(-1);

        const prevMonthBtn = document.createElement("button");
        const prevMonthImg = document.createElement("img");
        prevMonthImg.src = "{{ url_for('static', filename='素材/left.png') }}";
        prevMonthImg.alt = "Previous Month";
        prevMonthBtn.appendChild(prevMonthImg);
        prevMonthBtn.onclick = () => changeMonth(-1);

        const nextMonthBtn = document.createElement("button");
        const nextMonthImg = document.createElement("img");
        nextMonthImg.src = "{{ url_for('static', filename='素材/right.png') }}";
        nextMonthImg.alt = "Next Month";
        nextMonthBtn.appendChild(nextMonthImg);
        nextMonthBtn.onclick = () => changeMonth(1);

        const nextYearBtn = document.createElement("button");
        const nextYearImg = document.createElement("img");
        nextYearImg.src =
          "{{ url_for('static', filename='素材/doubleright.png') }}";
        nextYearImg.alt = "Next Year";
        nextYearBtn.appendChild(nextYearImg);
        nextYearBtn.onclick = () => changeYear(1);

        const monthYear = document.createElement("span");
        monthYear.textContent = `${months[month]} ${year}`;

        calendarHeader.appendChild(prevYearBtn);
        calendarHeader.appendChild(prevMonthBtn);
        calendarHeader.appendChild(monthYear);
        calendarHeader.appendChild(nextMonthBtn);
        calendarHeader.appendChild(nextYearBtn);
        calendarContainer.appendChild(calendarHeader);

        const daysOfWeek = ["日", "一", "二", "三", "四", "五", "六"];
        const daysOfWeekRow = document.createElement("div");
        daysOfWeekRow.classList.add("calendar-days");
        daysOfWeek.forEach((day) => {
          const dayCell = document.createElement("div");
          dayCell.classList.add("calendar-day");
          dayCell.textContent = day;
          daysOfWeekRow.appendChild(dayCell);
        });
        calendarContainer.appendChild(daysOfWeekRow);

        const daysRow = document.createElement("div");
        daysRow.classList.add("calendar-days");
        for (let i = 0; i < firstDay; i++) {
          const emptyCell = document.createElement("div");
          emptyCell.classList.add("calendar-day", "disabled");
          daysRow.appendChild(emptyCell);
        }
        for (let i = 1; i <= daysInMonth; i++) {
          const dayCell = document.createElement("div");
          dayCell.classList.add("calendar-day");
          dayCell.textContent = i;
          dayCell.onclick = () => updateDateInfo(i, month, year);

          if (
            i === today.getDate() &&
            month === today.getMonth() &&
            year === today.getFullYear()
          ) {
            dayCell.classList.add("today");
          }

          if (
            i === selectedDay &&
            month === selectedMonth &&
            year === selectedYear
          ) {
            dayCell.classList.add("selected");
          }

          daysRow.appendChild(dayCell);
        }
        calendarContainer.appendChild(daysRow);
      }

      function changeMonth(offset) {
        currentMonth += offset;
        if (currentMonth < 0) {
          currentMonth = 11;
          currentYear--;
        } else if (currentMonth > 11) {
          currentMonth = 0;
          currentYear++;
        }
        generateCalendar(currentMonth, currentYear);
        updateCalendarSelection();
      }

      function changeYear(offset) {
        currentYear += offset;
        generateCalendar(currentMonth, currentYear);
        updateCalendarSelection();
      }

      function showCalendar() {
        // 如果需要实现日历显示/隐藏功能
        const calendarContainer = document.getElementById("calendar-container");
        if (calendarContainer.style.display === "none") {
          calendarContainer.style.display = "flex";
        } else {
          calendarContainer.style.display = "none";
        }
      }
    </script>
  </body>
</html>
